<template>
  <div>
    <el-button type="primary" size="mini" @click="fitchData">回测参数</el-button>

    <div class="from-container">
      <el-form ref="form" :model="form" label-width="150px">
        <el-form-item label="指数 :">
          <el-select v-model="form.code" placeholder="请选择指数" value-key="id">
            <el-option
              v-for="item in codeList"
              :key="item.code"
              :label="'('+item.code+') '+item.name"
              :value="item.code"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="MA(均线) :">
          <el-select v-model="form.ma" placeholder="请选择均线">
            <el-option label="5日" value="5" />
            <el-option label="10日" value="10" />
            <el-option label="15日" value="15" />
            <el-option label="20日" value="20" />
            <el-option label="30日" value="30" />
            <el-option label="60日" value="60" />
            <el-option label="90日" value="90" />
          </el-select>
        </el-form-item>

        <el-row>
          <el-col :span="7">

            <el-form-item label="购买阈值 :">
              <el-select v-model="form.buyThreshold" placeholder="请选择购买阈值">
                <el-option label="1.01" value="1.01" />
                <el-option label="1.02" value="1.02" />
                <el-option label="1.03" value="1.03" />
                <el-option label="1.04" value="1.04" />
                <el-option label="1.05" value="1.05" />
                <el-option label="1.06" value="1.06" />
                <el-option label="1.07" value="1.07" />
                <el-option label="1.08" value="1.08" />
                <el-option label="1.09" value="1.09" />
                <el-option label="1.10" value="1.10" />
              </el-select>
            </el-form-item>
          </el-col>

          <el-col :span="7">
            <el-form-item label="出售阈值 :">
              <el-select v-model="form.sellThreshold" placeholder="请选择出售阈值">
                <el-option label="0.99" value="0.99" />
                <el-option label="0.98" value="0.98" />
                <el-option label="0.97" value="0.97" />
                <el-option label="0.96" value="0.96" />
                <el-option label="0.95" value="0.95" />
                <el-option label="0.94" value="0.94" />
                <el-option label="0.93" value="0.93" />
                <el-option label="0.92" value="0.92" />
                <el-option label="0.91" value="0.91" />
                <el-option label="0.90" value="0.90" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="手续费 :">
          <el-select v-model="form.serviceCharge" placeholder="请选择出售阈值">
            <el-option label="无" value="0" />
            <el-option label="0.1%" value="0.001" />
            <el-option label="0.15%" value="0.0015" />
            <el-option label="0.2%" value="0.002" />
          </el-select>
        </el-form-item>

        <el-row>
          <el-col :span="7">
            <el-form-item label="开始日期 :">
              <el-date-picker
                v-model="form.startDate"
                value-format="yyyy-MM-dd"
                type="date"
                placeholder="请选择开始日期"
                style="width: 100%;"
              />
            </el-form-item>
          </el-col>

          <el-col :span="7">
            <el-form-item label="结束日期 :">
              <el-date-picker
                v-model="form.endDate"
                value-format="yyyy-MM-dd"
                type="date"
                placeholder="请选择结束日期"
                style="width: 100%;"
              />
            </el-form-item>
          </el-col>
        </el-row>

      </el-form>
    </div>

    <el-button type="warning" size="mini">收益对比图</el-button>
    <div class="dashboard-editor-container">
      <el-row style="background:#fff;padding:16px 16px 0;margin-bottom:20px;">
        <line-chart :chart-data="trendLineChartData" />
      </el-row>
    </div>

    <el-button type="warning" size="mini">收益一览</el-button>
    <div class="dashboard-sy" style="padding: 20px">
      <el-table
        :data="incomeGlance"
        border
        stripe
        style="width: 100%"
      >
        <el-table-column
          prop="type"
          label="投资类型"
        />
        <el-table-column
          prop="year"
          label="投资时长 (年)"
        />
        <el-table-column
          prop="income"
          label="1000元投资收益"
        />
        <el-table-column
          prop="totalIncome"
          label="总收益率"
        />
        <el-table-column
          prop="yearIncome"
          label="年化收益率"
        />
      </el-table>
    </div>

    <el-button type="warning" size="mini">交易统计</el-button>
    <div class="dashboard-jy" style="padding: 20px">
      <el-table
        :data="incomeStatistics"
        bordertitle
        :show-header="false"
        style="width: 100%"
      >
        <el-table-column label="趋势投资盈亏统计">
          <el-table-column
            prop="title"
            label="项目"
          />
          <el-table-column
            prop="value"
            label="值"
          />
        </el-table-column>

      </el-table>
    </div>

    <el-button type="warning" size="mini">收益分布对比表</el-button>
    <div class="dashboard-sy" style="padding: 20px">
      <el-table
        :data="backData.annualProfits"
        border
        stripe
        style="width: 100%"
      >
        <el-table-column
          prop="year"
          label="年份"
        />
        <el-table-column
          prop="indexIncome"
          label="指数收益"
        />
        <el-table-column
          prop="trendIncome"
          label="趋势投资收益"
        />
      </el-table>
    </div>

    <el-button type="warning" size="mini">收益分布对比图</el-button>
    <div class="dashboard-editor-container">
      <el-row style="background:#fff;padding:16px 16px 0;margin-bottom:20px;">
        <bar-chart :chart-data="trendBarChartData" />
      </el-row>
    </div>

    <el-button type="warning" size="mini">交易明细</el-button>
    <div class="dashboard-sy" style="padding: 20px">
      <el-table
        :data="tradesDetial"
        border
        stripe
        style="width: 100%"
      >
        <el-table-column
          prop="winLose"
          label="盈/亏	"
        >
          <template slot-scope="scope">
            <el-tag
              :type="scope.row.winLose === '盈利' ? 'danger' : 'success'"
              disable-transitions
            >{{ scope.row.winLose }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column
          prop="buyDate"
          label="购买日期"
        />
        <el-table-column
          prop="buyClosePoint"
          label="购买盘点"
        />
        <el-table-column
          prop="sellDate"
          label="出售日期"
        />
        <el-table-column
          prop="sellClosePoint"
          label="出售盘点"
        />
        <el-table-column
          prop="winLoseRate"
          label="盈亏比率"
        >
          <template slot-scope="scope">
            <el-tag
              :type="scope.row.winLose === '盈利' ? 'danger' : 'success'"
              disable-transitions
            >{{ scope.row.winLoseRate }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column
          prop="income"
          label="1000元投资收益"
        />
      </el-table>
    </div>
  </div>

</template>

<script>
import LineChart from './components/LineChart'
import BarChart from './components/BarChart'

import trend from '@/trend.json'
import { backTest, getCodes } from '@/api/trend'

const trendLineChartData = {
  fundCode: '000300',
  dateData: trend.indexDatas.map(v => v.date),
  indexData: trend.indexDatas.map(v => v.closePoint),
  profitData: trend.profits.map(v => v.value)
}

const trendBarChartData = {
  fundCode: '000300',
  yearData: [],
  indexData: [],
  trendData: []
}

export default {
  name: 'DashboardUser',
  components: {
    LineChart,
    BarChart
  },
  data() {
    return {
      backData: {
        indexIncomeTotal: 0,
        winCount: 0,
        profits: [],
        lossCount: 0,
        avgLossRate: 0,
        indexIncomeAnnual: 0,
        trades: [],
        trendIncomeTotal: 0,
        indexStartDate: '2018-09-05',
        years: 0,
        indexDatas: [],
        indexEndDate: '2021-02-04',
        annualProfits: [],
        avgWinRate: 0,
        trendIncomeAnnual: 0
      },
      trendLineChartData: trendLineChartData,
      trendBarChartData: trendBarChartData,
      form: {
        code: '000300',
        ma: '20',
        buyThreshold: '1.01',
        sellThreshold: '0.99',
        serviceCharge: '0.001',
        startDate: '2018-09-07',
        endDate: '2021-02-04'
      },
      codeList: null,
      incomeGlance: [{
        type: '指数投资',
        year: '2.42',
        income: '3,308.40',
        totalIncome: '230.84%',
        yearIncome: '63.99%'
      }, {
        type: '趋势投资',
        year: '2.42',
        income: '3,308.40',
        totalIncome: '230.84%',
        yearIncome: '63.99%'
      }, {
        type: '相对收益',
        year: '2.42',
        income: '3,308.40',
        totalIncome: '230.84%',
        yearIncome: '63.99%'
      }],
      incomeStatistics: [
        {
          title: '总共交易次数',
          value: ''
        },
        {
          title: '盈利交易次数',
          value: ''
        },
        {
          title: '平均盈利比率',
          value: ''
        },
        {
          title: '亏损交易次数',
          value: ''
        },
        {
          title: '平均亏损比率',
          value: ''
        },
        {
          title: '胜率',
          value: ''
        }
      ],
      tradesDetial: []
    }
  },
  watch: {
    form: {
      handler: function(nowVal, oldVal) {
        this.fitchData()
      },
      deep: true
    }
  },
  created() {
    console.log('获取基金代码')
    this.fitchCodeList()
  },
  methods: {
    fitchData() {
      backTest(this.form).then(response => {
        this.backData = response
        // 收益对比图 计算逻辑
        this.trendLineChartData.fundCode = this.form.code
        this.trendLineChartData.dateData = response.indexDatas.map(v => v.date)
        this.trendLineChartData.indexData = response.indexDatas.map(v => v.closePoint)
        this.trendLineChartData.profitData = response.profits.map(v => v.value)
        // 收益分布对比图
        this.trendBarChartData.fundCode = this.form.code
        this.trendBarChartData.yearData = response.annualProfits.map(v => v.year)
        this.trendBarChartData.indexData = response.annualProfits.map(v => parseFloat(this.formatNumber(v.indexIncome * 100, 2, '.', '')))
        this.trendBarChartData.trendData = response.annualProfits.map(v => parseFloat(this.formatNumber(v.trendIncome * 100, 2, '.', '')))
        // 收益一览 计算逻辑
        // 指数投资
        console.log(this.backData.years)
        this.incomeGlance[0].year = this.formatNumber(this.backData.years, 2, '.', ',')
        this.incomeGlance[0].income = this.formatMoney((1 + this.backData.indexIncomeTotal) * 1000)
        this.incomeGlance[0].totalIncome = this.formatNumber(this.backData.indexIncomeTotal * 100, 2, '.', ',') + '%'
        this.incomeGlance[0].yearIncome = this.formatNumber(this.backData.indexIncomeAnnual * 100, 2, '.', ',') + '%'
        // 趋势投资
        this.incomeGlance[1].year = this.formatNumber(this.backData.years, 2, '.', ',')
        this.incomeGlance[1].income = this.formatMoney((1 + this.backData.trendIncomeTotal) * 1000)
        this.incomeGlance[1].totalIncome = this.formatNumber(this.backData.trendIncomeTotal * 100, 2, '.', ',') + '%'
        this.incomeGlance[1].yearIncome = this.formatNumber(this.backData.trendIncomeAnnual * 100, 2, '.', ',') + '%'
        // 相对收益
        this.incomeGlance[2].year = 'n/a'
        this.incomeGlance[2].income = this.formatMoney((this.backData.trendIncomeTotal - this.backData.indexIncomeTotal) * 1000)
        this.incomeGlance[2].totalIncome = this.formatNumber((this.backData.trendIncomeTotal - this.backData.indexIncomeTotal) * 100, 2, '.', ',') + '%'
        this.incomeGlance[2].yearIncome = this.formatNumber((this.backData.trendIncomeAnnual - this.backData.indexIncomeAnnual) * 100, 2, '.', ',') + '%'
        // 交易统计
        this.incomeStatistics[0].value = this.backData.winCount + this.backData.lossCount
        this.incomeStatistics[1].value = this.backData.winCount
        this.incomeStatistics[2].value = this.formatNumber(this.backData.avgWinRate * 100, 2, '.', ',') + '%'
        this.incomeStatistics[3].value = this.backData.lossCount
        this.incomeStatistics[4].value = this.formatNumber(this.backData.avgLossRate * 100, 2, '.', ',') + '%'
        this.incomeStatistics[5].value = this.formatNumber(this.backData.winCount / (this.backData.winCount + this.backData.lossCount) * 100, 2, '.', ',') + '%'
        // 收益分布对比表
        this.backData.annualProfits.forEach(annualProfit => {
          annualProfit.indexIncome = this.formatNumber(annualProfit.indexIncome * 100, 2, '.', ',') + '%'
          annualProfit.trendIncome = this.formatNumber(annualProfit.trendIncome * 100, 2, '.', ',') + '%'
        })
        // 交易明细
        this.backData.trades.forEach(trade => {
          var tradeDetail = {
            winLose: '',
            buyDate: '',
            buyClosePoint: '',
            sellDate: '',
            sellClosePoint: '',
            winLoseRate: '',
            income: ''
          }
          tradeDetail.winLose = trade.sellClosePoint > trade.buyClosePoint ? '盈利' : '亏损'
          tradeDetail.buyDate = trade.buyDate
          tradeDetail.buyClosePoint = trade.buyClosePoint
          tradeDetail.sellDate = trade.sellDate
          tradeDetail.sellClosePoint = trade.sellClosePoint === 0 ? 'n/a' : trade.sellClosePoint
          tradeDetail.winLoseRate = trade.sellClosePoint === 0 ? 'n/a' : this.formatNumber((trade.sellClosePoint - trade.buyClosePoint) * 100 / trade.buyClosePoint, 2, '.', '') + '%'
          tradeDetail.income = trade.sellClosePoint === 0 ? 'n/a' : this.formatMoney(trade.rate * 1000)
          this.tradesDetial.push(tradeDetail)
        })
      })
    },
    fitchCodeList() {
      getCodes().then(response => {
        console.log(response)
        if (response != null && response.length > 0) {
          this.codeList = response
          this.form.code = response[0].code
        }
      })
    },
    formatMoney(num) {
      var onum = num
      num = String(num)
      num = num.toString().replace(/\$|\,/g, '')
      if (isNaN(num)) {
        num = '0'
      }
      var sign = (onum === (num = Math.abs(num)))
      num = Math.floor(num * 100 + 0.50000000001)
      var cents = num % 100
      num = Math.floor(num / 100).toString()
      if (cents < 10) {
        cents = '0' + cents
      }
      for (var i = 0; i < Math.floor((num.length - (1 + i)) / 3); i++) {
        num = num.substring(0, num.length - (4 * i + 3)) + ',' +
          num.substring(num.length - (4 * i + 3))
      }
      return (((sign) ? '' : '-') + num + '.' + cents)
    },
    formatNumber(number, decimals, dec_point, thousands_sep) {
      /*
  * 参数说明：
  * number：要格式化的数字
  * decimals：保留几位小数
  * dec_point：小数点符号
  * thousands_sep：千分位符号
  * */
      number = (number + '').replace(/[^0-9+-Ee.]/g, '')
      var n = !isFinite(+number) ? 0 : +number
      var prec = !isFinite(+decimals) ? 0 : Math.abs(decimals)
      var sep = (typeof thousands_sep === 'undefined') ? ',' : thousands_sep
      var dec = (typeof dec_point === 'undefined') ? '.' : dec_point
      var s = ''
      var toFixedFix = function(n, prec) {
        var k = Math.pow(10, prec)
        return '' + Math.ceil(n * k) / k
      }

      s = (prec ? toFixedFix(n, prec) : '' + Math.round(n)).split('.')
      var re = /(-?\d+)(\d{3})/
      while (re.test(s[0])) {
        s[0] = s[0].replace(re, '$1' + sep + '$2')
      }

      if ((s[1] || '').length < prec) {
        s[1] = s[1] || ''
        s[1] += new Array(prec - s[1].length + 1).join('0')
      }
      return s.join(dec)
    }
  }
}
</script>

<style lang="scss" scoped>
.dashboard-editor-container {
  padding: 10px;
  //background-color: rgb(240, 242, 245);
  position: relative;

  .github-corner {
    position: absolute;
    top: 0px;
    border: 0;
    right: 0;
  }

  .chart-wrapper {
    background: #fff;
    padding: 16px 16px 0;
    margin-bottom: 32px;
  }
}

@media (max-width: 1024px) {
  .chart-wrapper {
    padding: 8px;
  }
}
</style>
